package com.sn.util;


import com.sn.constant.Windows;
import com.sn.net.Server;
import net.coobird.thumbnailator.Thumbnails;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * @Description: 截图加压缩
 * @Author: songbiao
 */
public class Capture {

    public byte[] capture(int width, int height) throws InterruptedException {
        if (Server.clients.size() > 0) {
            BufferedImage bufferedImage = null;
            ByteArrayOutputStream byteArrayOut = null;
            try {
                bufferedImage = new Robot()
                        .createScreenCapture(new Rectangle(0, 0, width, height));
                //图片压缩转二进制
                byteArrayOut= new ByteArrayOutputStream();
                BufferedImage compress = Thumbnails.of(bufferedImage).size(Windows.COMPRESS_WIDTH, Windows.COMPRESS_HEIGHT).asBufferedImage();
                ImageIO.write(compress
                        , "jpg", byteArrayOut);
                return byteArrayOut.toByteArray();
            }  catch (AWTException e) {
                System.out.println("截图失败...正在重试");
                Thread.sleep(500);
                capture(width,height);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (byteArrayOut!=null) {
                        byteArrayOut.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public byte[] capture() throws InterruptedException {
        return capture(Windows.DEFAULT_WIDTH, Windows.DEFAULT_HEIGHT);
    }

}
